package com.ypan.mail.handler;

import com.ypan.mail.common.excption.CommonEnum;
import com.ypan.mail.common.excption.CustomGlobalException;
import com.ypan.mail.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author ypan
 * @Date on 2021/4/21  15:02
 * @Desc
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomGlobalException.class)
    @ResponseBody
    public JsonResult customGlobalExceptionHandler(HttpServletRequest req, CustomGlobalException e){
        log.error("发生业务异常！原因是：{}",e.getErrorMsg());
        return JsonResult.error(e.getErrorCode(),e.getErrorMsg(),null);
    }


    /**
            * 处理空指针的异常
  * @param req
  * @param e
  * @return
          */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public JsonResult exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常！原因是:",e);
        return JsonResult.error(CommonEnum.BODY_NOT_MATCH);
    }

    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public JsonResult exceptionHandler(HttpServletRequest req, Exception e){
        log.error("未知异常！原因是:",e);
        return JsonResult.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }
}
